<template>
  <div class="flex">
    <!-- 筛选侧边栏 -->
    <div class="w-200px mr-20px">
      <ClassStudentTree @node-click="handleNodeClick" />
    </div>

    <!-- 主内容区 -->
    <div class="flex-1">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item>
            <!-- <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button> -->
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['school:device-gate-card:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>

            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['school:device-gate-card:create']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>

            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:device-gate-card:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
            <el-button
              type="danger"
              plain
              :disabled="isEmpty(checkedIds)"
              @click="handleDeleteBatch"
              v-hasPermi="['school:device-gate-card:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          row-key="id"
          v-loading="loading"
          :data="list"
          :stripe="true"
          :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange"
        >
          <el-table-column type="selection" width="55" />
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <el-table-column label="所属园区" align="center" prop="schoolCode">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SCHOOL_CODE" :value="scope.row.schoolCode" />
            </template>
          </el-table-column>
          <el-table-column label="班级" align="center" prop="className" />
          <el-table-column label="学生姓名" align="center" prop="studentName" />
          <el-table-column label="卡号" align="center" prop="cardNumber" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column label="操作" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['school:device-gate-card:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['school:device-gate-card:delete']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

      <!-- 表单弹窗：添加/修改 -->
      <DeviceGateCardForm ref="formRef" @success="getList" />

      <!-- 闸机卡片导入对话框 -->
      <GateCardImportForm ref="importFormRef" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DeviceGateCardApi, DeviceGateCard } from '@/api/school/smartDevice/gateCard'
import DeviceGateCardForm from './DeviceGateCardForm.vue'
import GateCardImportForm from './GateCardImportForm.vue' // 导入导入组件
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { ref, reactive, onMounted } from 'vue'

/** 闸机卡片 列表 */
defineOptions({ name: 'DeviceGateCard' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DeviceGateCard[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  cardNumber: undefined,
  schoolCode: undefined,
  classId: undefined,
  studentId: undefined,
  studentName: undefined,
  sort: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 组件引用
const importFormRef = ref()
const formRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceGateCardApi.getDeviceGateCardPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 用户导入 */
const handleImport = () => {
  importFormRef.value.open()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, {
    cascaderValue: [queryParams.schoolCode, queryParams.classId, queryParams.studentId]
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceGateCardApi.deleteDeviceGateCard(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除闸机卡片 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await DeviceGateCardApi.deleteDeviceGateCardList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: DeviceGateCard[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceGateCardApi.exportDeviceGateCard(queryParams)
    download.excel(data, '闸机卡片.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 处理节点点击
const handleNodeClick = (params: any) => {
  queryParams.schoolCode = params.schoolCode
  queryParams.classId = params.classId
  queryParams.studentId = params.studentId

  // 重新查询
  handleQuery()
}

/** 初始化 **/
onMounted(async () => {
  getList()
})
</script>
